package view;

import model.Major;
import model.Subject;
import service.MajorService;
import service.SubjectService;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.util.List;
import java.util.function.BiConsumer;

public class SubjectManagementPanel extends JPanel {
    // 添加字体常量
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font CONTENT_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    
    private SubjectService subjectService;
    private DefaultTableModel tableModel;
    private JTable subjectTable;
    
    public SubjectManagementPanel() {
        this.subjectService = new SubjectService();
        initComponents();
        loadSubjectData();
    }
    
    private void initComponents() {
        setLayout(new BorderLayout());
        
        // 设置全局字体
        UIManager.put("Label.font", CONTENT_FONT);
        UIManager.put("TextField.font", CONTENT_FONT);
        UIManager.put("TextArea.font", CONTENT_FONT);
        UIManager.put("Button.font", BUTTON_FONT);
        UIManager.put("Table.font", CONTENT_FONT);
        UIManager.put("TableHeader.font", TITLE_FONT);
        
        // 工具栏
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        
        JButton addButton = new JButton("新增课程");
        JButton deleteButton = new JButton("删除");
        JButton refreshButton = new JButton("刷新");
        
        addButton.addActionListener(e -> showAddDialog());
        deleteButton.addActionListener(e -> deleteSelectedSubject());
        refreshButton.addActionListener(e -> loadSubjectData());
        
        toolBar.add(addButton);
        toolBar.add(deleteButton);
        toolBar.add(refreshButton);
        
        add(toolBar, BorderLayout.NORTH);
        
        // 表格设置
        String[] columnNames = {"ID", "课程代码", "课程名称", "学分", "学时", "操作"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == columnNames.length - 1;
            }
            
            @Override
            public Class<?> getColumnClass(int column) {
                if (column == 3) return Double.class;  // 学分列
                if (column == 4) return Integer.class; // 学时列
                return Object.class;
            }
        };
        
        subjectTable = new JTable(tableModel);
        
        // 设置表格样式
        subjectTable.setRowHeight(25);
        subjectTable.getTableHeader().setPreferredSize(new Dimension(0, 30));
        subjectTable.getTableHeader().setFont(TITLE_FONT);
        subjectTable.setFont(CONTENT_FONT);
        
        // 设置列宽
        subjectTable.getColumnModel().getColumn(0).setPreferredWidth(50);   // ID
        subjectTable.getColumnModel().getColumn(1).setPreferredWidth(100);  // 课程代码
        subjectTable.getColumnModel().getColumn(2).setPreferredWidth(200);  // 课程名称
        subjectTable.getColumnModel().getColumn(3).setPreferredWidth(80);   // 学分
        subjectTable.getColumnModel().getColumn(4).setPreferredWidth(80);   // 学时
        subjectTable.getColumnModel().getColumn(5).setPreferredWidth(150);  // 操作列加宽
        
        // 设置操作列的渲染器和编辑器
        ButtonEditor buttonEditor = new ButtonEditor(e -> {
            String command = e.getActionCommand();
            int row = subjectTable.getSelectedRow();
            if (row != -1) {
                row = subjectTable.convertRowIndexToModel(row);
                handleAction(command, row);
            }
        });
        
        subjectTable.getColumnModel().getColumn(5)
            .setCellRenderer(buttonEditor.getRenderer());
        subjectTable.getColumnModel().getColumn(5)
            .setCellEditor(buttonEditor);
        
        // 设置表格的选择模式
        subjectTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 添加表格到滚动面板
        JScrollPane scrollPane = new JScrollPane(subjectTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        add(scrollPane, BorderLayout.CENTER);
    }
    
    private void loadSubjectData() {
        tableModel.setRowCount(0);
        List<Subject> subjects = subjectService.getAllSubjects();
        
        for (Subject subject : subjects) {
            Object[] rowData = {
                subject.getId(),
                subject.getSubjectCode(),
                subject.getSubjectName(),
                subject.getCredits(),
                subject.getHours(),
                "编辑 删除"
            };
            tableModel.addRow(rowData);
        }
        
        // 更新表格
        if (subjectTable.getRowSorter() != null) {
            ((TableRowSorter<?>)subjectTable.getRowSorter()).sort();
        }
    }
    
    private boolean validateForm(String code, String name, String credits, String hours, String majorCode) {
        if (code.isEmpty() || name.isEmpty() || credits.isEmpty() || 
            hours.isEmpty() || majorCode.isEmpty()) {
            return false;
        }
        
        try {
            double creditsValue = Double.parseDouble(credits);
            if (creditsValue <= 0) return false;
            
            int hoursValue = Integer.parseInt(hours);
            if (hoursValue <= 0) return false;
            
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    
    private void showAddDialog() {
        // 创建对话框
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), "新增课程", true);
        dialog.setLayout(new BorderLayout(10, 10));
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridLayout(5, 2, 5, 5));
        formPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        JTextField codeField = new JTextField();
        JTextField nameField = new JTextField();
        
        // 使用 SpinnerNumberModel 来限制��分的输入范围和步进值
        SpinnerNumberModel creditsModel = new SpinnerNumberModel(2.0, 0.5, 10.0, 0.5);
        JSpinner creditsSpinner = new JSpinner(creditsModel);
        
        // 创建学时选择下拉框
        JComboBox<String> hoursComboBox = new JComboBox<>();
        // 添加选项：每周1-5节课 × 2学时/节 × 18周
        for (int i = 1; i <= 5; i++) {
            int totalHours = i * 2 * 18;  // 每节课2学时，18周
            hoursComboBox.addItem(String.format("%d学时（每周%d节课）", totalHours, i));
        }
        
        // 添加学时说明标签
        JLabel hoursLabel = new JLabel("学时：");
        JLabel hoursHintLabel = new JLabel("（每节课2学时，共18周）");
        hoursHintLabel.setFont(new Font(hoursHintLabel.getFont().getName(), Font.ITALIC, 12));
        hoursHintLabel.setForeground(Color.GRAY);
        
        // 使用组合框选择专业
        JComboBox<String> majorComboBox = new JComboBox<>();
        loadMajors(majorComboBox);  // 加载专业列表
        
        formPanel.add(new JLabel("课程代码:"));
        formPanel.add(codeField);
        formPanel.add(new JLabel("课程名称:"));
        formPanel.add(nameField);
        formPanel.add(new JLabel("学分:"));
        formPanel.add(creditsSpinner);
        formPanel.add(hoursLabel);
        
        // 创建学时输入面板（包含下拉框和提示）
        JPanel hoursPanel = new JPanel(new BorderLayout());
        hoursPanel.add(hoursComboBox, BorderLayout.CENTER);
        hoursPanel.add(hoursHintLabel, BorderLayout.SOUTH);
        formPanel.add(hoursPanel);
        
        formPanel.add(new JLabel("专业代码:"));
        formPanel.add(majorComboBox);
        
        dialog.add(formPanel, BorderLayout.CENTER);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        saveButton.addActionListener(e -> {
            String code = codeField.getText().trim();
            String name = nameField.getText().trim();
            double credits = (double) creditsSpinner.getValue();
            
            // 从选择的文本中提取学时数
            String selectedHours = (String) hoursComboBox.getSelectedItem();
            int hours = Integer.parseInt(selectedHours.split("学时")[0]);
            
            String majorCode = majorComboBox.getSelectedItem().toString();
            
            if (code.isEmpty() || name.isEmpty() || majorCode.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "请填写所有必要信息！");
                return;
            }
            
            if (subjectService.addSubject(code, name, credits, hours, majorCode)) {
                loadSubjectData();
                dialog.dispose();
                JOptionPane.showMessageDialog(this, "添加成功！");
            } else {
                JOptionPane.showMessageDialog(dialog, "添加失败！", 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        
        cancelButton.addActionListener(e -> dialog.dispose());
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 设置字体
        codeField.setFont(CONTENT_FONT);
        nameField.setFont(CONTENT_FONT);
        creditsSpinner.setFont(CONTENT_FONT);
        hoursComboBox.setFont(CONTENT_FONT);
        majorComboBox.setFont(CONTENT_FONT);
        
        // 设置按钮字体
        saveButton.setFont(BUTTON_FONT);
        cancelButton.setFont(BUTTON_FONT);
        
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    // 加载专业列表
    private void loadMajors(JComboBox<String> majorComboBox) {
        MajorService majorService = new MajorService();
        List<Major> majors = majorService.getAllMajors();
        for (Major major : majors) {
            majorComboBox.addItem(major.getMajorCode());
        }
    }
    
    private void handleAction(String action, int row) {
        int id = (int) tableModel.getValueAt(row, 0);
        
        if (action.equals("编辑")) {
            showEditDialog(id);
        } else if (action.equals("删除")) {
            if (subjectService.deleteSubject(id)) {
                loadSubjectData();
            }
        }
    }
    
    private void showEditDialog(int subjectId) {
        // 获取课程信息
        Subject subject = subjectService.getSubjectById(subjectId);
        if (subject == null) {
            return;
        }

        // 创建对话框
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), "编辑课程", true);
        dialog.setLayout(new BorderLayout(10, 10));
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridLayout(5, 2, 5, 5));
        formPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        JTextField codeField = new JTextField(subject.getSubjectCode());
        JTextField nameField = new JTextField(subject.getSubjectName());
        
        // 使用 SpinnerNumberModel 来限制学分的输入范围和步进值
        SpinnerNumberModel creditsModel = new SpinnerNumberModel(
            subject.getCredits(), 0.5, 10.0, 0.5);
        JSpinner creditsSpinner = new JSpinner(creditsModel);
        
        // 创建学时选择下拉框
        JComboBox<String> hoursComboBox = new JComboBox<>();
        // 添加选项：每周1-5节课 × 2学时/节 × 18周
        for (int i = 1; i <= 5; i++) {
            int totalHours = i * 2 * 18;  // 每节课2学时，18周
            hoursComboBox.addItem(String.format("%d学时（每周%d节课）", totalHours, i));
        }
        // 设置当前值
        int weeklySlots = (int) Math.ceil(subject.getHours() / (2.0 * 18));
        hoursComboBox.setSelectedIndex(weeklySlots - 1);
        
        // 添加学时说明标签
        JLabel hoursLabel = new JLabel("学时：");
        JLabel hoursHintLabel = new JLabel("（每节课2学时，共18周）");
        hoursHintLabel.setFont(new Font(hoursHintLabel.getFont().getName(), Font.ITALIC, 12));
        hoursHintLabel.setForeground(Color.GRAY);
        
        // 使用组合框选择专业
        JComboBox<String> majorComboBox = new JComboBox<>();
        loadMajors(majorComboBox);  // 加载专业列表
        majorComboBox.setSelectedItem(subject.getMajorCode());
        
        // 课程代码不允许修改
        codeField.setEnabled(false);
        
        formPanel.add(new JLabel("课程代码:"));
        formPanel.add(codeField);
        formPanel.add(new JLabel("课程名称:"));
        formPanel.add(nameField);
        formPanel.add(new JLabel("学分:"));
        formPanel.add(creditsSpinner);
        formPanel.add(hoursLabel);
        
        // 创建学时输入面板（包含下拉框和提示）
        JPanel hoursPanel = new JPanel(new BorderLayout());
        hoursPanel.add(hoursComboBox, BorderLayout.CENTER);
        hoursPanel.add(hoursHintLabel, BorderLayout.SOUTH);
        formPanel.add(hoursPanel);
        
        formPanel.add(new JLabel("专业代码:"));
        formPanel.add(majorComboBox);
        
        dialog.add(formPanel, BorderLayout.CENTER);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        saveButton.addActionListener(e -> {
            String name = nameField.getText().trim();
            double credits = (double) creditsSpinner.getValue();
            
            // 从选择的文本中提取学时数
            String selectedHours = (String) hoursComboBox.getSelectedItem();
            int hours = Integer.parseInt(selectedHours.split("学时")[0]);
            
            String majorCode = majorComboBox.getSelectedItem().toString();
            
            if (name.isEmpty() || majorCode.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "请填写所有必要信息！");
                return;
            }
            
            subject.setSubjectName(name);
            subject.setCredits(credits);
            subject.setHours(hours);
            subject.setMajorCode(majorCode);
            
            if (subjectService.updateSubject(subject)) {
                loadSubjectData();
                dialog.dispose();
                JOptionPane.showMessageDialog(this, "修改成功！");
            } else {
                JOptionPane.showMessageDialog(dialog, "修改失败！", 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        
        cancelButton.addActionListener(e -> dialog.dispose());
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
        
        // 设置字体
        codeField.setFont(CONTENT_FONT);
        nameField.setFont(CONTENT_FONT);
        creditsSpinner.setFont(CONTENT_FONT);
        hoursComboBox.setFont(CONTENT_FONT);
        majorComboBox.setFont(CONTENT_FONT);
        
        // 设置按钮字体
        saveButton.setFont(BUTTON_FONT);
        cancelButton.setFont(BUTTON_FONT);
    }
    
    private void deleteSelectedSubject() {
        int selectedRow = subjectTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的课程！");
            return;
        }
        
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        String subjectName = (String) tableModel.getValueAt(selectedRow, 2);
        
        int confirm = JOptionPane.showConfirmDialog(this,
            "确定要删除课程 '" + subjectName + "' 吗？",
            "确认删除",
            JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            if (subjectService.deleteSubject(id)) {
                loadSubjectData();
                JOptionPane.showMessageDialog(this, "删除成功！");
            } else {
                JOptionPane.showMessageDialog(this, "删除失败！", 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
} 